/**
 * 时间日期相关操作
 */


/**
 * 时间格式化
 * 将 2018-09-23T11:54:16.000+0000 格式化成 2018/09/23 11:54:16
 * @param datetime 国际化日期格式
 */
export function format (datetime) {
  return formatWithSeperator(datetime, "/", ":");
}

/**
 * 时间格式化
 * 将 2018-09-23T11:54:16.000+0000 格式化成类似 2018/09/23 11:54:16
 * 可以指定日期和时间分隔符
 * @param datetime 国际化日期格式
 */
export function formatWithSeperator (datetime, dateSeprator, timeSeprator) {
  if (datetime != null) {
    const dateMat = new Date(datetime);
    const year = dateMat.getFullYear();
    const month = dateMat.getMonth() + 1;
    const day = dateMat.getDate();
    const hh = dateMat.getHours();
    const mm = dateMat.getMinutes();
    const ss = dateMat.getSeconds();
    const timeFormat = year + dateSeprator + month + dateSeprator + day + " " + hh + timeSeprator + mm + timeSeprator + ss;
    return timeFormat;
  }
}
export function timeGMTToString (str, format) {
  if (!str) return;

  if (typeof str == "object")
    return timespanToString(str.getTime(), format);
  if (typeof str == "number")
    return timespanToString(str, format);

  str = str.split(' ');
  var date_str = str[0];
  var time_str = "";
  if (str.length > 1)
    time_str = str[1];
  date_str = date_str.split('-');
  time_str = time_str.split(':');
  var date = new Date();
  date.setFullYear(date_str[0], date_str[1] - 1, date_str[2]);
  date.setHours(time_str[0], time_str.length > 1 ? time_str[1] : 0, time_str.length > 2 ? time_str[2] : 0, time_str.length > 3 ? time_str[3] : 0);
  return timespanToString(date.getTime(), format);
}

export function dateToString (timespan, format) {
  if (!timespan) return "-";

  var temp = /^\/Date\((\d+)\)\/$/i.exec(timespan);
  if (temp) {
    timespan = parseFloat(temp[1]);
    return timespanToString(timespan, format);
  }
  else {
    return "-";
  }
}

export function timespanToString (timespan, format) {
  if (!timespan) return "--";

  var date = new Date(timespan);
  var o = {
    "M+": date.getMonth() + 1, //month
    "d+": date.getDate(), //day
    "h+": date.getHours(), //hour
    "m+": date.getMinutes(), //minute
    "s+": date.getSeconds(), //second
    "q+": Math.floor((date.getMonth() + 3) / 3), //quarter
    "S": date.getMilliseconds() //millisecond
  }
  if (/(y+)/.test(format))
    format = format.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));

  for (var k in o) {
    if (new RegExp("(" + k + ")").test(format)) {
      format = format.replace(RegExp.$1,
        RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
    }
  }

  return format;
}
